package com.qding.park.manager.service.queue.biz;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.qding.park.common.core.exceptions.business.adapter.AdapterException;
import com.qding.park.common.core.exceptions.business.manager.adapterfactory.AdapterProxyCreateFail;
import com.qding.park.common.core.exceptions.system.NetWorkException;
import com.qding.park.common.utils.DateUtils;
import com.qding.park.common.utils.ListUtil;
import com.qding.park.common.utils.OrderNumUtil;
import com.qding.park.manager.adapter.factory.AdapterParkProxyFactory;
import com.qding.park.manager.cache.CarCacheInter;
import com.qding.park.manager.cache.ParkCacheInter;
import com.qding.park.manager.facade.queue.service.entity.RenewalSyncDTO;
import com.qding.park.manager.facade.queue.service.enums.ArkDeleteTagEnum;
import com.qding.park.manager.pojo.TbCar;
import com.qding.park.manager.pojo.TbFeetrade;
import com.qding.park.manager.pojo.TbMonthRent;
import com.qding.park.manager.pojo.TbParkspace;
import com.qding.park.manager.pojo.enums.MonthRentStatuEnum;
import com.qding.park.manager.pojo.enums.OrderServiceType;
import com.qding.park.manager.pojo.enums.OrderSourceEnum;
import com.qding.park.manager.pojo.enums.RecordStatusEnum;
import com.qding.park.manager.pojo.noncore.NcMonthRent;
import com.qding.park.manager.service.queue.dao.MongodbDao;
import com.qding.park.manager.service.queue.mapper.TbCarMapper;
import com.qding.park.manager.service.queue.mapper.TbFeetradeMapper;
import com.qding.park.manager.service.queue.mapper.TbMonthRentMapper;
import com.qding.park.manager.service.queue.mapper.TbParkspaceMapper;
import com.qding.park.target.common.adapter.PayFeeAdapter;
import com.qding.park.target.common.entity.AdMonthFeeOrder;

@Component("monthBiz")
public class MonthBiz {

    @Autowired
    private TbMonthRentMapper tbMonthRentMapper;

    @Autowired
    private TbParkspaceMapper tbParkspaceMapper;

    @Autowired
    private AdapterParkProxyFactory adapterParkProxyFactory;

    @Autowired
    private TbCarMapper tbCarMapper;

    @Autowired
    private CarCacheInter carCacheInter;

    @Autowired
    private ParkCacheInter parkCacheInter;

    @Autowired
    private TbFeetradeMapper tbFeetradeMapper;

    @Autowired
    private MongodbDao mongodbDao;

    public String cars2tel(List<TbCar> cars) {
        if (ListUtil.isEmpty(cars)) {
            return null;
        }

        return cars.get(0).getTel();
    }

    public String  cars2memberName(List<TbCar> cars){
        if (ListUtil.isEmpty(cars)) {
            return null;
        }

        return cars.get(0).getMemberName();
    }
    
    public String  cars2cardName(List<TbCar> cars){
        if (ListUtil.isEmpty(cars)) {
            return null;
        }

        return cars.get(0).getCardName();
    }
    
    public int cars2user(List<TbCar> cars) {
        if (ListUtil.isEmpty(cars)) {
            return 0;
        }

        return cars.get(0).getUserID();
    }

    public String cars2bjuser(List<TbCar> cars) {
        if (ListUtil.isEmpty(cars)) {
            return null;
        }

        return cars.get(0).getBjUserCode();
    }

    public Date cars2expiredTime(List<TbCar> cars) {
        if (ListUtil.isEmpty(cars)) {
            return null;
        }

        return cars.get(0).getCardExpiration();
    }

    public void monthPayedAfter(TbMonthRent tbMonthRent)
            throws AdapterProxyCreateFail, NetWorkException, AdapterException {

        int monthNum = tbMonthRent.getBuyMonths();

        // 得到车场编号
        int parkId = tbMonthRent.getParkID();
        int userId = tbMonthRent.getUserID();
        /******* 下发月卡通知单 ************/
        TbParkspace tbParkspace = tbParkspaceMapper.queryParkInfoByParkId(parkId);
        // 查询供应商信息
        int supplierId = tbParkspace.getSupplierId();
        // 车场提供的车场编号
        String parkCode = tbParkspace.getParkCode();
        String carNum = tbMonthRent.getCarNum();
        // int monthNUm=tbMonthRent.getBuyMonths();
        int amount = tbMonthRent.getCost();
        tbMonthRent.setStatus(MonthRentStatuEnum.PAYED_PARKED.getStatus());
        PayFeeAdapter adapterProxy = adapterParkProxyFactory.getPayFeeAdapter(String.valueOf(supplierId));
        AdMonthFeeOrder apMonthFeeOrder = adapterProxy.monthPay(parkCode, carNum, monthNum, amount,
                new Date(), tbMonthRent.getId());
        Date expireDate = apMonthFeeOrder.getExpireDate();
        tbCarMapper.updateExpireDate(parkId, userId, carNum, expireDate);
        // 更新月租订单属性
        tbMonthRentMapper.payedHandled(tbMonthRent);
    }

    @Transactional(rollbackFor = Throwable.class)
    public void monthFeeSync(RenewalSyncDTO dto) {
        ArkDeleteTagEnum isDelete = ArkDeleteTagEnum.getEnum(dto.getIsDelete());
        if (isDelete == ArkDeleteTagEnum.NOTDELETE) {

            String parkCode = dto.getParkCode();
            String supplyID = dto.getSupplyId();
            String carNum = dto.getCarNum();
            // 生成线上订单
            String payOrderID = OrderNumUtil.getOrderNum(parkCode, OrderServiceType.OUTLINE_MONTHRENT.getTag());
            TbParkspace parkspace = parkCacheInter.queryParkSpace(parkCode, Integer.valueOf(supplyID));

            int parkId = parkspace.getId();
            int monthcount = DateUtils.getMonthDiff(dto.getStartTime(), dto.getEndTime());
            // 线下缴费模式
            NcMonthRent ncMonthRent = new NcMonthRent();
            ncMonthRent.setParkPayId(dto.getOrderId());
            ncMonthRent.setCarNum(dto.getCarNum());
            ncMonthRent.setUserName("");
            ncMonthRent.setRechargeDate(dto.getAcceptanceTime());
            ncMonthRent.setShouldPaymentAmount(Integer.valueOf(dto.getShouldFeeMoney()));
            ncMonthRent.setPaymentAmount(Integer.valueOf(dto.getFeeMoney()));
            ncMonthRent.setMonthlyStartTime(dto.getStartTime());
            ncMonthRent.setMonthlyEndTime(dto.getEndTime());
            ncMonthRent.setOrderSource(OrderSourceEnum.OUTLINE.getType());
            ncMonthRent.setPayOrderID(payOrderID);

            List<TbCar> cars = carCacheInter.carNum2Info(carNum);

            ncMonthRent.setTel(cars2tel(cars));
            ncMonthRent.setUserId(cars2user(cars));
            ncMonthRent.setBjuserid(cars2bjuser(cars));
            ncMonthRent.setParkID(parkspace.getId());
            ncMonthRent.setParkName(parkspace.getName());
            ncMonthRent.setBuyMonths(monthcount);
            ncMonthRent.setCreate_date(new Date());
            ncMonthRent.setUpdate_date(new Date());

            if (!ListUtil.isEmpty(cars)) {
                int userId = cars2user(cars);
                String bjuserid = cars2bjuser(cars);
                String tel = cars2tel(cars);
                // monthlyBuyFee=tbCars.get(0).getMonthFee();
                String tradeId = OrderNumUtil.getOrderNum(userId, OrderServiceType.FEETRADE.getTag());
                String monthid = OrderNumUtil.getOrderNum(userId, OrderServiceType.OUTLINE_MONTHRENT.getTag());
                // appOrderlist.add(monthid);
                TbMonthRent tbMonthRent = new TbMonthRent();
                tbMonthRent.setParkID(parkId);
                tbMonthRent.setUserID(userId);
                tbMonthRent.setCarNum(carNum);
                tbMonthRent.setId(monthid);
                tbMonthRent.setParkName(parkspace.getName());
                tbMonthRent.setStatus(MonthRentStatuEnum.PAYED_PARKED.getStatus());
                tbMonthRent.setOldExpiredate(cars2expiredTime(cars));
                tbMonthRent.setExpiredate(dto.getEndTime());
                tbMonthRent.setBuyMonths(monthcount);
                tbMonthRent.setTradeID(tradeId);
                tbMonthRent.setCost(Integer.valueOf(dto.getShouldFeeMoney()));
                tbMonthRent.setRealPayCost(Integer.valueOf(dto.getFeeMoney()));
                tbMonthRent.setParkOrderId(dto.getOrderId());
                tbMonthRent.setOrderSource(OrderSourceEnum.OUTLINE.getType());
                tbMonthRent.setRemark("线下月租续费单");
                tbMonthRent.setCreate_date(new Date());
                tbMonthRent.setUpdate_date(new Date());
                tbMonthRentMapper.save(tbMonthRent);

                TbFeetrade tbFeetrade = new TbFeetrade();
                tbFeetrade.setId(tradeId);
                tbFeetrade.setUserID(tbMonthRent.getUserID());
                tbFeetrade.setParkID(tbMonthRent.getParkID());
                tbFeetrade.setFeeType(TbFeetrade.FeeTypeEnum.CAPITALFLOW_MONTH_PAY.getType());
                tbFeetrade.setFeeCost(Integer.valueOf(dto.getFeeMoney()));// 实付金额
                tbFeetrade.setBusinessID(tbMonthRent.getId());
                tbFeetrade.setChannel(TbFeetrade.ChannelEnum.CAPITALFLOW_LINE.getType());
                tbFeetrade.setStatus(RecordStatusEnum.EFFICIENCY.getStatus());
                tbFeetradeMapper.save(tbFeetrade);
            }
            mongodbDao.saveNcMonthRent(ncMonthRent);
        }
    }
}
